<template>
	<div v-loading="loading" class="promote-config">
		<div class="app-main-content-box form">
			<el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
				<!-- 员工 -->
				<app-main-sub-title title="员工推广提成" />
				<el-form-item label="启用提成功能：">
					<el-switch v-model="form.enableEmpBonus" />
				</el-form-item>
				<div class="mb-20" v-if="form.enableEmpBonus">
					<span class="font-14 form-hd_xing mr-10">请选择奖励方式: </span>
					<el-radio-group v-model="form.grantWay">
						<el-radio :label="1">
							<span class="mr-10">商户线下奖励</span>
							<el-tooltip effect="dark" placement="bottom">
								<div slot="content">表示员工推广奖励系统，只做记录。商户自己奖励给员工</div>
								<svg-icon icon-class="i-tips" />
							</el-tooltip>
						</el-radio>
						<el-radio :label="2">
							<span class="mr-10">线上分账</span>
							<el-tooltip effect="dark" placement="bottom">
								<div slot="content">
									表示产生员工推广奖励，系统自动分账至员工收款账号里<br />注：员工提成金额将按照T+1结算到员工收款账号；（T：指周一至周五，如周五产生交易将下周一结算）<br />如员工没设置收款账号，员工提成报表将记录发放失败，商户自行线下处理。
								</div>
								<svg-icon icon-class="i-tips" />
							</el-tooltip>
						</el-radio>
						<!-- <el-radio :label="3">
              <span class="mr-10">奖励至员工会员余额</span>
              <el-tooltip effect="dark" placement="bottom">
                <div slot="content">表示产生员工推广奖励，系统直接把奖励放入员工店铺会员卡余额里；<br />当员工还不是商户会员，员工提成报表将记录发放失败，商户自行线下处理。</div>
                <svg-icon icon-class="i-tips" />
              </el-tooltip>
            </el-radio> -->
					</el-radio-group>
				</div>
				<!-- <el-form-item> -->
				<el-collapse-transition>
					<el-card v-if="form.enableEmpBonus" style="margin-bottom:10px;">
						<el-form-item label="提成方式：" prop="empType">
							<!-- 开卡比例 -->
							<el-form-item v-if="form.openCardCalType === 1" prop="openCardPermill">
								<el-checkbox v-model="form.empType" label="openCard">顾客开卡按固定</el-checkbox>
								&nbsp;&nbsp;
								<el-select v-model="form.openCardCalType" @change="openCardChange" placeholder="请选择" :disabled="!form.empType.includes('openCard')">
									<el-option
									  v-for="item in openCardSelectOpt"
									  :key="item.value"
									  :label="item.label"
									  :value="item.value">
									</el-option>
								</el-select>
								 计算提成，开卡金额 ≥
								<el-input
									v-model="form.openCardCalLeastFee"
									:disabled="!form.empType.includes('openCard')"
									placeholder="请输入" 
									size="small" 
									class="input" 
									maxlength="4" />
								元时，提成开卡金额的
								<el-input 
									v-model="form.openCardPermill" 
									:disabled="!form.empType.includes('openCard')"
									placeholder="请输入" 
									size="small" 
									class="input" 
									maxlength="4" />
								%
							</el-form-item>
							<el-form-item v-else prop="openCardFixedFee">
								<el-checkbox v-model="form.empType" label="openCard">顾客开卡按固定</el-checkbox>
								&nbsp;&nbsp;
								<el-select v-model="form.openCardCalType" @change="openCardChange" placeholder="请选择" :disabled="!form.empType.includes('openCard')">
									<el-option
									  v-for="item in openCardSelectOpt"
									  :key="item.value"
									  :label="item.label"
									  :value="item.value">
									</el-option>
								</el-select>
								 计算提成，开卡金额 ≥
								<el-input
									v-model="form.openCardCalLeastFee"
									:disabled="!form.empType.includes('openCard')"
									placeholder="请输入" 
									size="small" 
									class="input" 
									maxlength="4" />
								元时，提成
								<el-input 
									v-model="form.openCardFixedFee" 
									:disabled="!form.empType.includes('openCard')"
									placeholder="请输入" 
									size="small" 
									class="input" />
								元
							</el-form-item>
							
							<!-- 充值比例 -->
							<el-form-item v-if="form.rechargeCalType === 1" prop="firstRechargePermill">
								<el-checkbox v-model="form.empType" label="firstRecharge">顾客充值（含充值开卡）按固定</el-checkbox>
								&nbsp;&nbsp;
								<el-select v-model="form.rechargeCalType" @change="rechargeChange" placeholder="请选择" :disabled="!form.empType.includes('firstRecharge')">
									<el-option
									  v-for="item in openCardSelectOpt"
									  :key="item.value"
									  :label="item.label"
									  :value="item.value">
									</el-option>
								</el-select>
								计算提成，充值金额 ≥
								<el-input v-model="form.rechargeCalLeastFee"
									placeholder="请输入" 
									:disabled="!form.empType.includes('firstRecharge')"
									size="small" 
									class="input" 
									maxlength="4" />
								元时，提成充值金额的
								<el-input v-model="form.firstRechargePermill"
									:disabled="!form.empType.includes('firstRecharge')" 
									placeholder="请输入" size="small"
									class="input" 
									maxlength="4" />
								%
							</el-form-item>
							<el-form-item v-else prop="rechargeFixedFee">
								<el-checkbox v-model="form.empType" label="firstRecharge">顾客充值（含充值开卡）按固定</el-checkbox>
								&nbsp;&nbsp;
								<el-select v-model="form.rechargeCalType" @change="rechargeChange" placeholder="请选择" :disabled="!form.empType.includes('firstRecharge')">
									<el-option
									  v-for="item in openCardSelectOpt"
									  :key="item.value"
									  :label="item.label"
									  :value="item.value">
									</el-option>
								</el-select>
								计算提成，充值金额 ≥
								<el-input v-model="form.rechargeCalLeastFee"
									placeholder="请输入" 
									:disabled="!form.empType.includes('firstRecharge')"
									size="small" 
									class="input" 
									maxlength="4" />
								元时，提成
								<el-input v-model="form.rechargeFixedFee"
									:disabled="!form.empType.includes('firstRecharge')" placeholder="请输入" size="small"
									class="input" />
								元
							</el-form-item>

							<!-- 消费比例 -->
							<el-form-item v-if="form.orderPayCalType === 1" prop="orderPayPermill">
								<el-checkbox v-model="form.empType" label="payPermill">顾客消费按固定</el-checkbox>
								&nbsp;&nbsp;
								<el-select v-model="form.orderPayCalType" @change="orderPayChange" placeholder="请选择" :disabled="!form.empType.includes('payPermill')">
									<el-option
									  v-for="item in openCardSelectOpt"
									  :key="item.value"
									  :label="item.label"
									  :value="item.value">
									</el-option>
								</el-select>
								计算提成，消费实付金额 ≥
								<el-input v-model="form.orderPayCalLeastFee"
									placeholder="请输入" 
									:disabled="!form.empType.includes('payPermill')"
									size="small" 
									class="input" 
									maxlength="4" />
								元时，提成消费金额的
								<el-input v-model="form.orderPayPermill"
									:disabled="!form.empType.includes('payPermill')" placeholder="请输入" size="small"
									class="input" maxlength="4" />
								%
							</el-form-item>
							<el-form-item v-else prop="orderPayFixedFee">
								<el-checkbox v-model="form.empType" label="payPermill">顾客消费按固定</el-checkbox>
								&nbsp;&nbsp;
								<el-select v-model="form.orderPayCalType" @change="orderPayChange" placeholder="请选择" :disabled="!form.empType.includes('payPermill')">
									<el-option
									  v-for="item in openCardSelectOpt"
									  :key="item.value"
									  :label="item.label"
									  :value="item.value">
									</el-option>
								</el-select>
								计算提成，消费实付金额 ≥
								<el-input v-model="form.orderPayCalLeastFee"
									placeholder="请输入" 
									:disabled="!form.empType.includes('payPermill')"
									size="small" 
									class="input" 
									maxlength="4" />
								元时，提成
								<el-input v-model="form.orderPayFixedFee"
									:disabled="!form.empType.includes('payPermill')" placeholder="请输入" size="small"
									class="input" />
								元
							</el-form-item>
							
							
							<el-form-item v-if="form.empType.includes('payPermill')" prop="empAspect">
								生效业务：
								<el-checkbox-group v-model="empAspect">
									<el-checkbox label="1">商城</el-checkbox>
									<el-checkbox label="2">点餐</el-checkbox>
									<el-checkbox label="4">预订</el-checkbox>
									<el-checkbox label="8">码牌支付</el-checkbox>
								</el-checkbox-group>
							</el-form-item>

							<el-form-item>
								注：<br/>
								1、商城/点餐/预订/码牌支付订单实付金额指订单商品优惠后的总额，不含运费<br/>
								2、提成金额 > 实付金额时，提成会直接发放失败
							</el-form-item>
						</el-form-item>
					</el-card>
				</el-collapse-transition>
				<!-- </el-form-item> -->
				<!-- 顾客 -->
				<app-main-sub-title title="顾客推广奖励" />
				<el-form-item label="启用奖励功能：">
					<el-switch v-model="form.enableMemberBonus" />
				</el-form-item>
				<!-- <el-form-item> -->
				<el-collapse-transition>
					<el-card v-if="form.enableMemberBonus" style="margin-bottom:10px;">
						<!-- <span>如果顾客不是会员则会奖励失效</span> -->
						<!-- <el-form-item label-width="20px">
              <el-tag>
                <i class="el-icon-warning" />&nbsp;温馨提示：如果顾客不是会员则奖励会失效。
              </el-tag>
            </el-form-item> -->

						<el-tabs v-model="activeName">
							<el-tab-pane v-for="(tabItem, tabIdx) in form.memberConfigVos" :key="tabItem.name"
								:label="tabItem.label" :name="tabItem.name">
								<el-form-item
									v-if="(tabItem.bonusType !== 1) && (tabItem.bonusType === ~~activeName + 1)"
									label="限制设置：" :prop="`memberConfigVos[${tabIdx}].limitAmount`"
									:rules="{required: tabItem.openLimitSetting,validator: validateLimitAmount, trigger: ['blur', 'change']}">
									<el-checkbox v-model="tabItem.openLimitSetting">{{tabItem.name | limitLabel}}
									</el-checkbox>
									<div class="mx-10" style="display: inline-block;">
										<el-input v-model="tabItem.limitAmount" size="small" class="input"
											:disabled="!tabItem.openLimitSetting" />
									</div>
									<span>元享受奖励</span>

									<p v-show="tabItem.name === '2'">注：订单实付金额指订单商品优惠后的总额，不含运费</p>
								</el-form-item>
								<el-form-item v-if="(tabItem.bonusType ==3) " label="参与商品："
									:prop="`memberConfigVos[${tabIdx}].productType`"
									:rules="{required: true,validator: validateLimitAmount, trigger: ['blur', 'change']}">
									<el-radio-group v-model="tabItem.productType">
										<el-radio :label="1">全部商品</el-radio>
										<el-radio :label="2">部分商品</el-radio>
									</el-radio-group>
									<div v-if="tabItem.productType == '2'" class="add_text">
										<el-button @click="openAddDialog('add')">添加商品</el-button>&emsp;&emsp;&emsp;
										<el-button type="text" @click="openAddDialog('edit')">
											已选{{selectedProduct.length}}件商品</el-button>
									</div>
								</el-form-item>

								<!-- 奖励的类型 -->
								<el-form-item v-if="tabItem.bonusType === ~~activeName + 1" label="奖励的类型："
									:prop="`memberConfigVos[${tabIdx}].memberType`"
									:rules="{required: true, validator: validateMemberType, trigger: ['blur', 'change']}">
									<el-checkbox-group v-model="tabItem.memberType"
										@change="(val) => memberTypeChange(val, tabIdx)">>
										<el-checkbox label="balance" name="memberType">余额</el-checkbox>
										<el-checkbox label="points" name="memberType">积分</el-checkbox>
										<el-checkbox label="cardCoupon" name="memberType">卡券
										</el-checkbox>
										<!-- <el-checkbox :disabled="form.memberType.includes('cardCoupon')" label="coupon" name="memberType">优惠券(已弃用)
                    </el-checkbox> -->
									</el-checkbox-group>
								</el-form-item>

								<!-- 奖励会员余额 -->
								<el-form-item
									v-if="tabItem.memberType.includes('balance') && tabItem.bonusType === ~~activeName + 1"
									label="赠送会员余额：" :prop="`memberConfigVos[${tabIdx}].balanceBonus`"
									:rules="{required: tabItem.memberType.includes('balance'), validator: validateBalanceBonus, trigger: ['blur', 'change']}">
									<el-input v-model="tabItem.balanceBonus" placeholder="请输入" size="small"
										class="input" maxlength="10" />&nbsp;&nbsp;元
								</el-form-item>

								<!-- 奖励会员积分 -->
								<el-form-item
									v-if="tabItem.memberType.includes('points') && tabItem.bonusType === ~~activeName + 1"
									label="赠送会员积分：" :prop="`memberConfigVos[${tabIdx}].pointsBonus`"
									:rules="{required: tabItem.memberType.includes('points'), validator: validatePointsBonus, trigger: ['blur', 'change']}">
									<el-input v-model="tabItem.pointsBonus" placeholder="请输入" maxlength="7" size="small"
										class="input" />&nbsp;&nbsp;个
								</el-form-item>

								<!-- 奖励优惠券 券v2 -->
								<!-- 这里不能用v-show 表单校验问题 -->
								<el-form-item
									v-if="(tabItem.memberType.includes('cardCoupon')||tabItem.memberType.includes('coupon')) && tabItem.bonusType === ~~activeName + 1"
									:rules="{type: 'array', required: tabItem.memberType.includes('cardCoupon')||tabItem.memberType.includes('coupon'), validator: validateCouponBonus, trigger: 'change'}"
									:label="tabItem.memberType.includes('cardCoupon')?'赠送卡券':'赠送券'"
									:prop="`memberConfigVos[${tabIdx}].bonusCouponVos`">
									<div class="card-coupon-container">
										<el-table :data="tabItem.bonusCouponVos" border stripe size="small"
											empty-text="暂未配置" style="width: 100%">
											<el-table-column prop="couponId" label="批次号" />
											<el-table-column prop="couponName" label="卡券名称" />
											<el-table-column prop="couponType" label="卡券类型">
												<template slot-scope="scope">
													{{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType]||"--" }}
												</template>
											</el-table-column>
											<el-table-column prop="amount" label="数量" width="170px">
												<template slot-scope="scope">
													<el-input-number v-model="scope.row.amount" :min="1" :max="99"
														maxlength="2" label="数量" style="margin-top: 18px" />
												</template>
											</el-table-column>
											<el-table-column label="操作" width="80">
												<template slot-scope="scope">
													<el-button type="text" @click="delCardCoupon(scope.$index)">删除
													</el-button>
												</template>
											</el-table-column>
										</el-table>
										<el-button v-if="tabItem.memberType.includes('cardCoupon')"
											:disabled="tabItem.bonusCouponVos && tabItem.bonusCouponVos.length>=10"
											type="text" icon="el-icon-plus" style="display:block"
											@click.native.prevent="openDialogCardCouponTable">增加卡券
										</el-button>
										<!--<el-button-->
										<!--  v-if="form.memberType.includes('coupon')"-->
										<!--  disabled="false"-->
										<!--  type="text"-->
										<!--  icon="el-icon-plus"-->
										<!--  style="display:block"-->
										<!--  @click.native.prevent="openCouponList"-->
										<!--&gt;增加券-->
										<!--</el-button>-->
										<div style="font-size: 12px;color: #606266">
											单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
									</div>
								</el-form-item>

							</el-tab-pane>
						</el-tabs>

					</el-card>
				</el-collapse-transition>
				<!-- </el-form-item> -->
				<!-- 提交 -->
				<el-form-item>
					<el-button round type="primary" @click="onSubmit">保 存</el-button>
					<el-button round @click="initData">重 置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 券1.0 筛选表格 -->
		<dialog-coupon-list ref="dialogCouponList" />
		<!--券2.0 筛选表格 -->
		<DialogCardCouponTable ref="dialogCardCouponTable"
			:card-coupon-type="['cash','discount','exchange','cash_wx_pay','times','gift']"
			:has-checked-ids="hasCheckedCardCouponIds" />
		<addProductDialog ref="addProductDialog" @dialogClose="dialogClose" />
		<selectedDialog ref="selectedDialog" @dialogClose="dialogClose" />

	</div>
</template>

<script>
	import DialogCouponList from '@/components/DialogCouponList'
	import DialogCardCouponTable from '@/components/DialogCardCouponTable'
	import addProductDialog from './addProductDialog.vue'
	import selectedDialog from './selectedDialog.vue'
	import {
		getVipInviteConfig,
		updateVipInviteConfig,
		getSelectedNum,
		getChooseProducts,
		productSaveOrUpdate,
	} from '@/api/vip'
	import {
		validateCustomADecimal,
		validate0To20ADecimal
	} from '@/utils/validate'
	import {
		debounce
	} from '@/utils/index'
	import valiteModule from './valiteModule'
	import {
		cloneDeep
	} from 'lodash-es'
	const LABEL = {
		'1': '顾客单次充值金额≥',
		'2': '顾客单次消费订单金额≥'
	}
	const bonusWayListsMap = {
		balance: 1,
		points: 2,
		cardCoupon: 4
	}
	const bonusWayListsMapF = {
		1: 'balance',
		2: 'points',
		4: 'cardCoupon'
	}
	export default {
		components: {
			DialogCouponList,
			DialogCardCouponTable,
			addProductDialog,
			selectedDialog,
		},
		props: {
			tabName: {
				type: String,
				require: true
			}
		},
		data() {
			const _this = this
			/**
			 * 表单校验方法相关
			 */
			// 百分比0.1到100校验
			const validatePercent1to99 = (rule, value, callback, text) => {
				if (!value) {
					callback(new Error(text))
				} else if (!validateCustomADecimal(value, 2, [100])) {
					callback(new Error('请输入0.1~100正整数，正小数（小数位不超过1位）'))
				} else {
					callback()
				}
			}
			const validatePercent1to20 = (rule, value, callback) => {
				const reg = new RegExp(
					'^((0\\.[1-9])|([1-9])|([1][0-9])|([1][0-9])\\.\\d{1}|([1-2]{0,2}\\.\\d{1})|20)$')
				if (!value) {
					callback(new Error('请输入比例'))
				} else if (!reg.test(value)) {
					callback(new Error('请输入0.1~20正整数，正小数（小数位不超过1位）'))
				} else {
					callback()
				}
			}
			
			const validatePercent1to6 = (rule, value, callback) => {
				let strValue = Number(value)
				if(!strValue || strValue > 999999){
					callback(new Error('请输入0~999999整数，小数位不超过2位'))
				}else{
					callback()
				}
			}

			// 如果启用 员工提成的方式 必须选择其中一种
			const validateEmpType = (rule, value, callback) => {
				if (this.form.enableEmpBonus && value.length === 0) {
					callback(new Error('请至少选择一种员工提成方式'))
				} else {
					callback()
				}
			}

			// 如果启用 员工消费提成 必须选择其中一种
			const validateEmpAspect = (rule, value, callback) => {
				if (this.form.empType.includes('payPermill') && this.empAspect.length === 0) {
					callback(new Error('请至少选择一项消费提成生效业务'))
				} else {
					callback()
				}
			}

			// 这里不是箭头函数，并且这里的this不是vue实例的this，用了bind
			const validateOpen = function(rule, value, callback) {
				if (
					!_this.form.enableEmpBonus ||
					!_this.form.empType.includes(this)
				) {
					callback()
				} else {
					switch (_this.form.grantWay) {
						case 1:
							validatePercent1to99(rule, value, callback, '请输入比例')
							break;
						case 2:
							validatePercent1to20(rule, value, callback)
							break;
						default:
							callback(new Error('校验错误'))
							break;
					}
				}
			}
			const validate_Open = function(rule, value, callback) {
				if (
					!_this.form.enableEmpBonus ||
					!_this.form.empType.includes(this)
				) {
					callback()
				} else {
					validatePercent1to6(rule, value, callback)
				}
			}

			//  校验优惠券id是否已经过期
			// const validateCouponBonusId = (rule, value, callback) => {
			//   if (this.$isNull(value)) {
			//     callback('请选择优惠券')
			//   } else if (this.invalidCouponIds.includes(value)) {
			//     callback(new Error('该券已过期或已删除，请更换其它券'))
			//   } else {
			//     callback()
			//   }
			// }
			return {
				empAspect: [],
				/**
				 * 表单校验字段相关
				 */
				rules: {
					// 员工提成的方式
					empType: [{
						required: true,
						validator: validateEmpType,
						trigger: 'change'
					}],
					empAspect: [{
						required: true,
						validator: validateEmpAspect,
						trigger: 'change'
					}],
					// 员工提成的方式 顾客开卡比例
					openCardPermill: [{
						required: this.openLimitSetting,
						validator: validateOpen.bind('openCard'),
						trigger: ['blur', 'change']
					}],
					openCardFixedFee: [{
						required: this.openLimitSetting,
						validator: validate_Open.bind('openCard'),
						trigger: ['blur', 'change']
					}],
					// 员工提成的方式 顾客首充充值比例
					firstRechargePermill: [{
						required: true,
						validator: validateOpen.bind('firstRecharge'),
						trigger: ['blur', 'change']
					}],
					rechargeFixedFee: [{
						required: true,
						validator: validate_Open.bind('firstRecharge'),
						trigger: ['blur', 'change']
					}],
					//员工提成的方式 顾客消费比例
					orderPayPermill: [{
						required: true,
						validator: validateOpen.bind('payPermill'),
						trigger: ['blur', 'change']
					}],
					orderPayFixedFee: [{
						required: true,
						validator: validate_Open.bind('payPermill'),
						trigger: ['blur', 'change']
					}],
					// 优惠券判断失效
					// couponBonusId: [
					//   {
					//     required: true,
					//     validator: validateCouponBonusId,
					//     trigger: ['blur', 'change']
					//   }
					// ],
				},
				// 配置
				// 状态
				loading: false,
				// 数据
				hasCheckedCardCouponIds: [], // 当前已选择的优惠券
				// invalidCouponIds: [], // 失效的优惠券id
				form: {
					enableEmpBonus: false, // 是否启用员工提成
					empType: [], // 员工提成方式
					grantWay: 1, // 奖励方式
					enableMemberBonus: false, // 是否启用顾客奖励
					// memberType: [], // 顾客奖励方式
					
					openCardCalType: 1,
					rechargeCalType:1,
					orderPayCalType:1,
					
					memberConfigVos: [{
							label: '开卡奖励',
							name: '0',
							openLimitSetting: false,
							bonusCouponVos: [],
							bonusType: 1, // 奖励的行为1开卡奖励2充值奖励3消费奖励
							bonusWayLists: [],
							balanceBonus: '', // 赠送余额
							pointsBonus: '', //  赠送会员积分
							limitAmount: '', // 限制设置金额
							memberType: [],
						},
						{
							label: '充值奖励',
							name: '1',
							openLimitSetting: false,
							bonusCouponVos: [],
							bonusType: 2, // 奖励的行为1开卡奖励2充值奖励3消费奖励
							bonusWayLists: [], //  1余额2积分4卡券
							balanceBonus: '', // 赠送余额
							pointsBonus: '', //  赠送会员积分
							limitAmount: '', // 限制设置金额
							memberType: []
						},
						{
							label: '消费奖励',
							name: '2',
							openLimitSetting: false,
							bonusCouponVos: [],
							bonusType: 3, // 奖励的行为1开卡奖励2充值奖励3消费奖励
							bonusWayLists: [],
							balanceBonus: '', // 赠送余额
							pointsBonus: '', //  赠送会员积分
							limitAmount: '', // 限制设置金额
							memberType: [],
							productType: 1
						}
					]
				},
				openCardSelectOpt: [
					{
					  value: 1,
					  label: '比例'
					}, {
					  value: 2,
					  label: '金额'
					}
				],
				activeName: '0',
				dataPar: {
					arr: '1'
				},
				// 已选商品数量
				selectedNum: 0,
				// 已选商品
				selectedProduct: []
			}
		},
		watch: {
			tabName(val) {
				if (val === 'config') {
					this.initData()
				}
			},
			'form.empType'(val) {
				if (val.length !== 0) {
					this.$refs.form.clearValidate(['empType'])
				}
			},
			'form.grantWay'() {
				this.$refs.form.validateField(['openCardPermill'])
				this.$refs.form.validateField(['firstRechargePermill'])
				this.$refs.form.validateField(['orderPayPermill'])
			},
			// // 'form.memberType'(val) {
			//   if (val.length !== 0) {
			//     this.$refs.form.clearValidate(['memberType'])
			//   }
			// },
		},
		filters: {
			limitLabel(val) {
				return LABEL[val] || ''
			}
		},
		mounted() {
			this.initData()
		},
		methods: {
			/**
			 *  获取数据
			 */
			// 获取推广配置
			initData() {
				this.loading = true
				getVipInviteConfig().then(res => {
					res.data.empType = []
					// res.data.memberType = []
					if (res.data.openCardPermill || res.data.openCardFixedFee) {
						res.data.empType.push('openCard')
						res.data.openCardCalLeastFee = res.data.openCardCalLeastFee / 100
						res.data.openCardPermill = res.data.openCardPermill / 10
						res.data.openCardFixedFee = res.data.openCardFixedFee / 100
					}
					if (res.data.firstRechargePermill || res.data.rechargeFixedFee) {
						res.data.empType.push('firstRecharge')
						res.data.rechargeCalLeastFee = res.data.rechargeCalLeastFee / 100
						res.data.firstRechargePermill = res.data.firstRechargePermill / 10
						res.data.rechargeFixedFee = res.data.rechargeFixedFee / 100
					}
					if (res.data.orderPayPermill || res.data.orderPayFixedFee) {
						res.data.empType.push('payPermill')
						res.data.orderPayCalLeastFee = res.data.orderPayCalLeastFee / 100
						res.data.orderPayPermill = res.data.orderPayPermill / 10
						res.data.orderPayFixedFee = res.data.orderPayFixedFee / 100
					}

					if (res.data.memberConfigVos) {
						const cloneData = cloneDeep(res.data.memberConfigVos)
						Object.assign(res.data.memberConfigVos, this.form.memberConfigVos)
						cloneData.forEach((item, index) => {
							item.memberType = []
							item.bonusWayLists.forEach(bonusWay => {
								if (bonusWay) {
									item.memberType.push(bonusWayListsMapF[bonusWay])
								}
							})
							// 判断是否有余额
							if (item.balanceBonus) {
								item.balanceBonus = item.balanceBonus
							}
							// // 判断是否有积分
							// if (item.pointsBonus) {
							//   item.memberType.push('points')
							// }
							// 判断是否有券

							if (!item.bonusCouponVos || !item.bonusCouponVos.length) {
								item.bonusCouponVos = []
							}
							res.data.memberConfigVos.forEach((i, idx) => {
								if (i.bonusType === item.bonusType) {
									Object.assign(i, item)
								}
								i.limitAmount && (i.openLimitSetting = true)
							})
						})
						// res.data.memberConfigVos.forEach((i, idx) => {
						//   if(cloneData[idx] && (i.bonusType === cloneData[idx].bonusType)) {
						//     Object.assign(i, cloneData[idx])
						//   }
						//   i.limitAmount && (i.openLimitSetting = true)
						// })
					} else {
						res.data.memberConfigVos = this.form.memberConfigVos
					}
					
					if(res.data.orderTypeList){
						this.empAspect = []
						res.data.orderTypeList.forEach(el => {
							this.empAspect.push(String(el))
						})
					}
					this.form = res.data
				}).finally(() => {
					this.loading = false
				})

				this.getChooseProducts()
			},
			getChooseProducts() {
				// 获取已选商品
				getChooseProducts({}).then((res) => {
					if (res.code == 0) {
						this.selectedProduct = res.data;
					}
				});
			},

			// 打开新增商品弹窗
			openAddDialog(type) {
				console.log(type)
				let {
					form: {
						id
					},
					selectedProduct
				} = this
				type == 'add' ? this.$refs.addProductDialog.openDialog(selectedProduct) : this.$refs.selectedDialog
					.openDialog(selectedProduct)
			},
			dialogClose(data) {
				this.selectedProduct = data.chooseProducts
			},
			// // 打开已选商品弹窗
			// openSelectDialog(){
			//   this.$refs.selectedDialog.openDialog(this.form.id)
			// },

			// 根据ids获取当前优惠券列表
			// initCouponList() {
			//   const ids = this.hasCheckedCardCouponIds
			//   this.loading = true
			//   getCouponListByIds({ ids })
			//     .then(res => {
			//       if (res.data) {
			//         res.data.forEach(v => {
			//           if (v.status === 3 || v.logicDelete) {
			//             this.invalidCouponIds.push(v.id)
			//           }
			//         })
			//       }
			//     })
			//     .finally(() => {
			//       this.loading = false
			//     })
			// },
			
			// 开卡方式切换，清空值
			openCardChange(){
				this.form.openCardPermill = null
				this.form.openCardFixedFee = null
			},
			rechargeChange(){
				this.form.firstRechargePermill = null
				this.form.rechargeFixedFee = null
			},
			orderPayChange(){
				this.form.orderPayPermill = null
				this.form.orderPayFixedFee = null
			},
			
			/**
			 *  按钮组
			 */
			// 保存推广配置
			onSubmit: debounce(function() {
				let {
					form: {
						memberConfigVos: list
					},
					selectedProduct
				} = this
				let flagPar = ''
				if (list && list.length > 0) {
					list.forEach(item => {
						if (item.bonusType == 3) {
							flagPar = item
						}
					})
				}
				if (flagPar && flagPar.productType == 2 && selectedProduct.length < 1) {
					this.$message({
						type: 'error',
						message: '请选择参与商品之后再进行保存'
					})
					return
				}
				this.$refs.form.validate(valid => {
					if (valid) {
						// 格式化数据
						const params = cloneDeep(this.form)
						if (!params.empType.includes('openCard')) {
							delete params.openCardPermill
							delete params.openCardFixedFee
						} else {
							params.openCardCalLeastFee = params.openCardCalLeastFee ? this.$math.mul(params
								.openCardCalLeastFee, 100, 0) : null
							params.openCardPermill = params.openCardPermill ? this.$math.mul(params
								.openCardPermill, 10, 0) : null
							params.openCardFixedFee = params.openCardFixedFee ? this.$math.mul(params
								.openCardFixedFee, 100, 0) : null
						}
						
						if (!params.empType.includes('firstRecharge')) {
							delete params.firstRechargePermill
							delete params.rechargeFixedFee
						} else {
							params.rechargeCalLeastFee = params.rechargeCalLeastFee ? this.$math.mul(params
								.rechargeCalLeastFee, 100, 0) : null
							params.firstRechargePermill = params.firstRechargePermill ? this.$math.mul(
								params.firstRechargePermill, 10, 0) : null
							params.rechargeFixedFee = params.rechargeFixedFee ? this.$math.mul(params
								.rechargeFixedFee, 100, 0) : null
						}
						
						if (!params.empType.includes('payPermill')) {
							delete params.orderPayPermill
							delete params.orderPayFixedFee
						} else {
							params.orderPayCalLeastFee = params.orderPayCalLeastFee ? this.$math.mul(params
								.orderPayCalLeastFee, 100, 0) : null
							params.orderPayPermill = params.orderPayPermill ? this.$math.mul(params
								.orderPayPermill, 10, 0) : null;
							params.orderPayFixedFee = params.orderPayFixedFee ? this.$math.mul(params
								.orderPayFixedFee, 100, 0) : null
							
							params.orderTypeList = []
								this.empAspect.forEach(el => {
									params.orderTypeList.push(el)
								})
						}
						
						if (params.enableMemberBonus) {
							params.memberConfigVos.forEach(i => {
								if (!i.memberType.includes('balance')) {
									delete i.balanceBonus
								}
								if (!i.openLimitSetting) {
									delete i.limitAmount
								}
								if (!i.memberType.includes('points')) {
									delete i.pointsBonus
								}
								i.bonusWayLists = [...new Set(i.bonusWayLists)]
								if (!i.memberType.includes('cardCoupon')) {
									delete i.bonusCouponVos
								}
							})
						} else {
							delete params.memberConfigVos
						}

						// 删除多选状态
						delete params.empType
						// 删除 memberConfigVos memberType 没选择的项
						if (params.memberConfigVos) {
							params.memberConfigVos = params.memberConfigVos.filter(i => i.memberType
								.length)
						}
						// delete params.memberType
						this.loading = true
						updateVipInviteConfig(params)
							.then(res => {
								this.loading = false
								this.$notify({
									title: '成功',
									message: '保存成功',
									type: 'success',
									duration: 2000,
									offset: 40
								})
								this.initData()
							})
							.catch(() => {
								this.loading = false
							})
						productSaveOrUpdate({
							addProductIds: selectedProduct,
							inviteConfigId: params.id,
						}).then((res) => {
							if (res.code == 0) {}
						});
					}
				})
			}, 300),

			// 新增优惠券
			openCouponList() {
				this.hasCheckedCardCouponIds = []
				this.form.memberConfigVos[this.activeName].bonusCouponVos.forEach(v => {
					this.hasCheckedCardCouponIds.push(v.couponId)
				})
				this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 1).then(res => {
					this.$refs.form.clearValidate(['bonusCouponVos'])
					const params = Object.assign({}, res)
					// const params = {
					//   couponId: res.id,
					//   amount: 1,
					//   couponName: res.couponName
					// }
					this.form.memberConfigVos[this.activeName].bonusCouponVos.push(params)
				})
			},

			//  新增优惠券 v2
			openDialogCardCouponTable() {
				this.hasCheckedCardCouponIds = []
				this.form.memberConfigVos[this.activeName].bonusCouponVos.forEach(v => {
					this.hasCheckedCardCouponIds.push(v.couponId)
				})
				this.$nextTick(() => {
					this.$refs.dialogCardCouponTable.open().then(res => {
						this.$refs.form.clearValidate(['couponBonus'])
						this.form.memberConfigVos[this.activeName].bonusCouponVos = this.form
							.memberConfigVos[this.activeName].bonusCouponVos.concat(res)
					})
				})
			},

			// 删除优惠券
			delCardCoupon(index) {
				this.$refs.form.clearValidate(['bonusCouponVos[' + index + '].couponId'])
				this.form.memberConfigVos[this.activeName].bonusCouponVos.splice(index, 1)
				if (this.form.memberConfigVos[this.activeName].bonusCouponVos.length <= 10) {
					this.$refs.form.validateField(['bonusCouponVos'])
				}
			},

			/**
			 * 状态
			 */
			// 赠送类型
			memberTypeChange(val, idx) {
				if (!val) return
				const bonusWayLists = val.map((i, idx) => bonusWayListsMap[val[idx]])
				this.form.memberConfigVos[idx].bonusWayLists = bonusWayLists
				if (!val.includes('cardCoupon') && !val.includes('coupon')) {
					this.form.memberConfigVos[idx].bonusCouponVos = []
				}
				// console.log(this.form.memberConfigVos[idx].bonusWayLists)
			},

			...valiteModule
		}
	}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	/* 券列表 */
	.card-coupon-container {
		max-width: 800px;
		margin-bottom: 10px;

		//.coupon-list {
		//  margin-top: 18px;
		//  width: 100%;
		//  display: flex;
		//  align-items: center;
		//  justify-content: space-between;
		//
		//  .coupon-info {
		//    min-width: 250px;
		//    color: #606266;
		//    margin-right: 20px;
		//    line-height: 1.2;
		//  }
		//}
	}

	.add_text {
		color: #86c8ff;
	}

	.promote-config {
		.form {
			.input {
				width: 120px;
			}

			.input-append-250 {
				width: 250px;
			}
		}

		.form-hd_xing::before {
			content: '*';
			color: #EC4040;
			margin-right: 4px;
		}
	}
</style>
